tidyverse: ggplot2

้ƒญ่€€ไป

ggplot2 ๅฅ—ไปถ

่ถ…็ดšๅ—ๆญก่ฟŽ

  • ๅŒ…ๅซๆ–ผ tidyverse ไน‹ไธญ
  • ่ฆ–่ฆบๅŒ–็š„ๆ–‡ๆณ•
  • ๅฐ‡่ฎŠๆ•ธๆŒ‡ๅฎšๅœจ aes() ไน‹ไธญ
ggplot(df, aes()) +
  geom_xxx()

ๅŸบๆœฌ็š„็ตฑ่จˆๅœ–ๅฝข

  • ๆ•ฃไฝˆๅœ–๏ผšgeom_point()
  • ็ทšๅœ–๏ผšgeom_line()
  • ็›ดๆ–นๅœ–๏ผšgeom_histogram()
  • ็›’้ฌšๅœ–๏ผšgeom_boxplot()
  • ้•ทๆขๅœ–๏ผšgeom_bar()

็นชๅœ–ๅ‰ๅ…ˆ๏ผˆๅฎ‰่ฃ๏ผ‰่ผ‰ๅ…ฅ้€™ไบ›ๅฅ—ไปถ

install.packages(c("tidyverse", "gapminder"))
library(tidyverse)
library(gapminder)

ๆ•ฃไฝˆๅœ–

gapminder_2007 <- gapminder %>%
  filter(year == 2007)
scatter <- ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) +
  geom_point() +
  theme_minimal()
scatter

็ทšๅœ–

north_asia <- gapminder %>%
  filter(country %in% c("China", "Japan", "Taiwan", "Korea, Rep."))
line_plot <- ggplot(north_asia, aes(x = year, y = gdpPercap, colour = country)) +
  geom_line() +
  theme_minimal()
line_plot

็›ดๆ–นๅœ–

histogram <- ggplot(gapminder_2007, aes(x = gdpPercap)) +
  geom_histogram(bins = 20) +
  theme_minimal()
histogram

็›’้ฌšๅœ–

box_plot <- ggplot(gapminder_2007, aes(x = continent, y = gdpPercap)) +
  geom_boxplot() +
  theme_minimal()
box_plot

้•ทๆขๅœ–

gdpPercap_2007_na <- gapminder %>%
  filter(year == 2007 & country %in% c("China", "Japan", "Taiwan", "Korea, Rep."))

bar_plot <- ggplot(gdpPercap_2007_na, aes(x = country, y = gdpPercap)) +
  geom_bar(stat = "identity") +
  theme_minimal()
bar_plot

้šจๅ ‚็ทด็ฟ’

็ทด็ฟ’่ณ‡ๆ–™้›†

csv_url <- "https://storage.googleapis.com/learn-r-the-easy-way.appspot.com/hh.csv"
hh <- read.csv(csv_url, stringsAsFactors = FALSE, fileEncoding = 'utf8')

ๆฌ„ไฝๅฎš็พฉ

  • district: ่กŒๆ”ฟๅ€
  • hh: ๆˆถๆ•ธ
  • disposable_income_in_thousands: ๅฏๆ”ฏ้…ๆ‰€ๅพ—๏ผˆๆ–ฐๅฐๅนฃๅƒๅ…ƒ๏ผ‰
  • year: ๅนดไปฝ

ๅคงๅฎ‰ๅ€ใ€ไธญๆญฃๅ€่ˆ‡ไฟก็พฉๅ€็š„ๅนณๅ‡ๆฏๆˆถๅฏๆ”ฏ้…ๆ‰€ๅพ—็ทšๅœ–

ๆ‰€ๆœ‰่กŒๆ”ฟๅ€็š„ๆฏๆˆถๅฏๆ”ฏ้…ๆ‰€ๅพ—็›’้ฌšๅœ–

ๅนณๅ‡ๆฏๆˆถๅฏๆ”ฏ้…ๆ‰€ๅพ—็š„ๆœ€ๆ–ฐๆŽ’ๅ